<?php

namespace app\admin\controller\crm;

use app\common\controller\Backend;
use think\Db;
use think\Session;
use app\admin\controller\crm\Query;
/**
 * B端客户管理
 *
 * @icon fa fa-circle-o
 */
class Buser extends Backend
{
    
    /**
     * Buser模型对象
     * @var \app\admin\model\Buser
     */
    protected $model = null;
    protected $admin_data = '';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Buser;
        $adminData= Session::get("admin");
        //查询当前admin权限
        $linkAdmin = Db::name('Admin');
        $this->admin_data = $linkAdmin->field('a.*,g.id AS gid,g.name,g.pid')->alias('a')
            ->join('fa_auth_group_access u','a.id = u.uid','LEFT')
            ->join('fa_auth_group g','u.group_id = g.id','LEFT')
            ->where(array('a.id'=>$adminData['id']))->find();
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("genderList", $this->model->getGenderList());
        $this->view->assign("qqFriendList", $this->model->getQqFriendList());
        $this->view->assign("wecahtFriendList", $this->model->getWecahtFriendList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    protected $modelValidate = true; //是否开启Validate验证，默认是false关闭状态
    protected $modelSceneValidate = true; //是否开启模型场景验证，默认是false关闭状态

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['company'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['company'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','username','qq','wechat','mobile','email','status','gender','birthday','createtime','qq_friend','wecaht_friend','station','typelist']);
                $row->visible(['company']);
				$row->getRelation('company')->visible(['company']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $user_verification=false;
                $this->user_verification($this->admin_data['pid'],'销售部',$user_verification);//判断是否是销售部门
                if(!$user_verification){
                    $this->error('您不是销售部的小伙伴,不能添加客户');
                }
                $allot=new \app\admin\model\Allot();
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    if(empty($params['contacts'])){
                        $this->error('请输入联系人名字');
                    }
                    //判断当前用户是有效还是无效
                    if(empty($params['qq'])&&empty($params['wechat'])&&empty($params['mobile'])){
                        //有效用户|意向客户
                        $this->error(__('请输入QQ||微信||手机号码其中一种联系方式'));
                    }
                    if($params['mobile']){
                        $yanTel = preg_match('/^1[3|4|5|6|7|8]\d{9}/',$params['mobile']);
                        if(!$yanTel){
                            $this->error('手机号码格式不正确');
                        }
                        //有效用户
                        $params['typelist'] = '1';
                        $status = '1';
                        $admin_id = session('admin.id');
                    }else{
                        //无效用户|无意向客户
                        $params['typelist'] = '2';
                        $status = '0';
                        //销售专员意外的人随意分配客户
                        if($this->admin_data['name']=='销售部经理'){
                            //查询所有销售
                            $groupArray = array();
                            $this->di_group(array(13),$groupArray);
                            $linkAdmin = Db::name('auth_group_access');
                            $adminIdArray = $linkAdmin->where(array('group_id'=>array('IN',$groupArray)))->column('uid');
                            $admin_id = $adminIdArray[rand(0,count($adminIdArray)-1)];
                        }else{
                            //分配当前销售专员
                            $admin_id = session('admin.id');
                        }
                    }
                    $product_id = explode(',',$params['product_id']);
                    if(empty($product_id)){
                        $this->error('请选择推广产品');
                    }
                    $add = false;
                    //查询期限时间
                    $linkPlan = Db::name('product');
                    $qi = Db::name('allot_expire')->where(array('id'=>1))->value('expire');
                    $allot_date = date('Y-m-d H:i:s',time());
                    $expire_date = date('Y-m-d H:i:s',strtotime('+'.$qi.' days'));
                    $result = $this->model->allowField(true)->save($params);
                    if($result){
                        foreach ($product_id as $k=>$v){
                            $planData = $linkPlan->where(array('id'=>$v,'type'=>1))->find();
                            if($planData){
                                $params['product_id'] = $v;
                                //添加客户资料成功，添加线索
                                $buser_id = $this->model->id;
                                $allotFiled['buser_id'] = $buser_id;
                                $allotFiled['admin_id'] = $admin_id;
                                $allotFiled['typelist'] = '1';
                                $allotFiled['allot_date'] = $allot_date;
                                $allotFiled['expire_date'] = $expire_date;
                                $allotFiled['product_id'] = $v;
                                $allotFiled['status'] = $status;
                                /*    $allot->validate('Allot.add');*/
                                $result_allot = $allot->insertGetId($allotFiled);
                                if($result_allot !== false)
                                {
                                    $add = true;
                                } else {
                                    Db::rollback();
                                    $this->error('发配记录失败，请刷新后重试');
                                }
                            }else{
                                Db::rollback();
                                $this->error('未发布第'.($k+1).'个产品');
                            }
                        }
                    }
                    if($add){
                        //操作成功
                        Db::commit();
                        $linkQuery = new  Query();
                        $linkQuery->index($buser_id);//抓取B端数据
                        $this->success();
                    }else{
                        //写入失败
                        Db::rollback();
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL,$type=1)
    {
        //判断是走那过来的数据
        $allotData = array('status'=>'');
        $linkAllot = new \app\admin\model\Allot;
        if($type==2){
            //走分配客户管理过来

            $allotData = $linkAllot->where(array('id'=>$ids,'userlist'=>'1'))->find();
            if(!$allotData){
                $this->error('不存在当前客户');
            }
            $ids = $allotData['buser_id'];
        }
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $allotField['typelist'] = isset($params['typelist'])?$params['typelist']:'';
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    if(empty($params['qq'])&&empty($params['wechat'])&&empty($params['mobile'])){
                        $this->error('请输入QQ||微信||手机号码其中一种联系方式');
                    }
                    if($params['mobile']){
                        $yanTel = preg_match('/^1[3|4|5|6|7|8]\d{9}/',$params['mobile']);
                        if(!$yanTel){
                            $this->error('输入的手机号格式不正确');
                        }
                        //有效用户
                        $params['typelist'] = '1';
                    }else{
                        //无效用户
                        $params['typelist'] = '2';
                    }
                    $result = $this->model->where(array('id'=>$ids))->update($params);
                    if($type==2&&$allotField['typelist']&&$allotData['status']==6){
                        //修改合作状态
                        $linkAllot->where(array('id'=>$allotData['id']))->update(array('typelist'=>$allotField['typelist']));
                    }
                    if ($result !== false) {
                        $linkQuery = new  Query();
                        $linkQuery->index($ids);//抓取B端数据
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign("type", $type);
        $this->view->assign('allotData',$allotData);
        $this->view->assign("heList", $this->model->getTypeList());
        return $this->view->fetch();
    }
    /**
     * 导入
     */
    public function import()
    {
        $user_verification=false;
        $this->user_verification($this->admin_data['pid'],'销售部',$user_verification);//判断是否是销售部门
        if(!$user_verification){
            $this->error('您不是销售部的小伙伴,不能导入客户');
        }
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);

        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }
        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }
        $linkBuser = Db::name('Buser');
        $linkAllot = Db::name('Allot');
        $linkProduct = Db::name('product');
        $linkQi = Db::name('allot_expire');
        //查询所有产品
        $productData = $linkProduct->where(array('type'=>1))->select();
        if(!$productData){
            $this->error('未查询到正在使用中的产品数据');
        }
        //查询所有销售
        $groupArray = array();
        $this->di_group(array(13),$groupArray);
        $linkAdmin = Db::name('auth_group_access');
        $adminIdArray = $linkAdmin->where(array('group_id'=>array('IN',$groupArray)))->column('uid');
        //查询分配期限
        $qi= $linkQi->where(array('id'=>1))->value('expire');
        $allot_date = date('Y-m-d H:i:s',time());
        $expire_date = date('Y-m-d H:i:s',strtotime('+'.$qi.' days'));
        Db::startTrans();//开启事务
        try {
           /* $this->model->saveAll($insert);*/
           $addCount = 1;
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $addCount++;
                $values = [];
                for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    if(empty($row['username'])){
                        $this->error(__('第'.$currentRow.'行的客户名称为空,请检查导入文件'));
                    }
                    $buserData = $linkBuser->where(array('username'=>$row['username']))->find();
                    if($buserData){
                        $this->error('第'.$currentRow.'行的客户名称已经被占用');
                    }
                    if(empty($row['contacts'])){
                        $this->error('请输入联系人');
                    }
                    if($row['gender']!=1&&$row['gender']!=2){
                        $this->error('第'.$currentRow.'行的性别值不正确');
                    }
                    //不存在当前客户
                    if(empty($row['qq'])&&empty($row['wechat'])&&empty($row['mobile'])){
                        $this->error('第'.$currentRow.'行的客户请输入QQ||微信号||手机号里其中一种联系方式');

                    }
                    if($row['mobile']){
                        $yanTel = preg_match('/^1[3|4|5|6|7|8]\d{9}/',$row['mobile']);
                        if(!$yanTel){
                            $this->error('第'.$currentRow.'行手机格式不正确');
                        }
                        //有效用户
                        $typelist = '1';
                        $status = '1';
                    }else{
                        //无效用户
                        $typelist = '2';
                        $status = '0';
                    }
                    $buserField = array(
                        'username'=>$row['username'],
                        'pinname'=>$row['pinname'],
                        'qq'=>$row['qq'],
                        'wechat'=>$row['wechat'],
                        'email'=>$row['email'],
                        'mobile'=>$row['mobile'],
                        'typelist'=>$typelist,
                        'contacts'=>$row['contacts'],
                        'gender'=>$row['gender'],
                        'hobby'=>$row['hobby'],
                        'station'=>$row['station'],
                    );
                    $buserAdd = $linkBuser->insertGetId($buserField);
                    if(!$buserAdd){
                        Db::rollback();
                        $this->error('第'.$currentRow.'行客户数据记录失败，请从新导入');
                    }
                    if(!in_array($this->admin_data['id'],$adminIdArray)){
                        //随机一个销售专员
                        $admin_id = $adminIdArray[rand(0,count($adminIdArray)-1)];
                    }else{
                        if($typelist!=1&&$this->admin_data['id']==6){
                            //无效用户&&销售部经理
                            $admin_id = $adminIdArray[rand(0,count($adminIdArray)-1)];
                        }else{
                            $admin_id = $this->admin_data['id'];
                        }
                    }
                    $allotField = array();
                    foreach ($productData as $ko=>$vo){
                        $allotField[] = array(
                            'buser_id'=>$buserAdd,
                            'admin_id'=>$admin_id,
                            'product_id'=>$vo['id'],
                            'expire_date'=>$expire_date,
                            'allot_date'=>$allot_date,
                            'status' => $status
                        );
                    }
                    //写入分配数据
                    $allotAdd = $linkAllot->insertAll($allotField);
                    if(!$allotAdd){
                        Db::rollback();
                        $this->error('第'.$currentRow.'行分配数据录入失败');
                    }
                    /*     $insert[] = $row;*/
                }
            }
            //提交操作
            if($addCount==$allRow){
                //操作成功
                Db::commit();
                $this->success();
            }else{
                Db::rollback();
                $this->error('操作失败');
            }

        } catch (\think\exception\PDOException $exception) {
            $this->error($exception->getMessage());
        } catch (\think\Exception $e) {
            $this->error($e->getMessage());
        }

    }
}
